<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: {2021/5/22}
 * Time: {20:38}
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

namespace app\admin\business;

use app\common\model\mysql\AdminUser as ModelObj;
use think\Exception;
use think\facade\Log;
use think\facade\Session;

class AdminUser
{
    protected $modelObj = null;

    public function __construct()
    {
        $this->modelObj = new ModelObj();
    }

    /**
     * @param array $data
     * @return bool
     * @throws Exception
     */
    public function checkLogin(array $data = []): bool
    {
        //验证
        $validate = new \app\common\validate\AdminUser();
        if (!$validate->scene('login')->check($data)) {
            throw new Exception($validate->getError());
        }
        //获取用户信息
        try {
            $userAdmin = $this->modelObj->getAdminUserByUserAdmin($data['username']);
        } catch (\Exception $e) {
            Log::error($e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            throw new Exception("系统内部异常");
        }
        if (!$userAdmin) {
            throw new Exception("用户不存在");
        }
        if ($userAdmin['password'] != md5($data['password'] . $userAdmin['code'])) {
            throw new Exception("用户名和密码不正确");
        }

        //更新数据表
        $update_date = [
            "last_login_time" => time(),
            "last_login_ip" => ip2long(request()->ip())
        ];
        try {
            $result = $this->modelObj->updateById($userAdmin['id'], $update_date);
        } catch (\Exception $e) {
            Log::error($e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            throw new Exception("更新数据失败");
        }
        //密码正确 记录session
        if (!$result) {
            throw new Exception("数据更新失败");
        }
        Session::set(config('admin.session_admin'), md5(time()) . "-" . $userAdmin['id'] . "-" . md5(time() . rand(111111, 9999999999)));
        return true;
    }

}